package com.lin.servlet;

import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.lin.service.CategoryServiceImpl;
import com.lin.service.ICategoryService;
import com.lin.utils.BaseServlet;
import com.lin.utils.UUIDUtils;
import com.lin.vo.Category;

@WebServlet(name = "AdminCategoryServlet", urlPatterns = {"/adminCategoryServlet"})
public class AdminCategoryServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private ICategoryService categoryService = new CategoryServiceImpl();
	public String findAllCategory(HttpServletRequest request, HttpServletResponse response) {
		List<Category> categorys = categoryService.findAllCategory();
		request.setAttribute("categorys", categorys);
		return "change:/adminjsps/admin/category/list.jsp";
	}
	public String loginQuit(HttpServletRequest request,HttpServletResponse response){
		request.getSession().invalidate();
		return "orient:/adminjsps/login.jsp";
	}
	public String addEdit(HttpServletRequest request, HttpServletResponse response){
	/*	String sign = request.getParameter("sign");*/
		return "change:/adminjsps/admin/category/add.jsp";
	
		
	}
	public String add(HttpServletRequest request, HttpServletResponse response){
		String cname = request.getParameter("cname");
		Category category =new Category();
		category.setCname(cname);
		category.setCid(UUIDUtils.getUUID());
		// 调用业务层方法
		categoryService.addCategory(category);
		return findAllCategory(request, response);
	}
	public String findByCategoryCid(HttpServletRequest request, HttpServletResponse response){
		String cid=request.getParameter("cid");
		String sign = request.getParameter("sign");
		Category category=categoryService.findByCategoryCid(cid);
		request.setAttribute("category", category);
		if("0".equals(sign)){
			return "change:/adminjsps/admin/category/mod.jsp";
		}else{
			return "change:/adminjsps/admin/category/del.jsp";
		}
	
	}
	
	public String updateCategory(HttpServletRequest request, HttpServletResponse response){
		Category category = new Category();
			try {
				BeanUtils.populate(category, request.getParameterMap());
				categoryService.updateCategory(category);
			} catch (Exception e) {
				e.printStackTrace();
			}	
		return findAllCategory(request,response);
	}
	
	public String deleteByCategoryCid(HttpServletRequest request, HttpServletResponse response){
		Category category = new Category();
		try {
			BeanUtils.populate(category, request.getParameterMap());
			categoryService.deleteByCategoryCid(category);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return findAllCategory(request,response);
	}
	
}
